package com.scs.application.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.CacheUtils;
import com.scs.application.modules.sys.entity.Flow;
import com.scs.application.modules.sys.entity.FlowButton;
import com.scs.application.modules.sys.mapper.FlowButtonMapper;
import com.scs.application.modules.sys.mapper.FlowMapper;
import com.scs.application.modules.sys.service.FlowButtonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 */
@Service
public class FlowButtonServiceImpl extends BaseServiceImpl<FlowButtonMapper, FlowButton> implements FlowButtonService {
    @Autowired
    FlowMapper flowMapper;

    @Override
    public boolean saveOrUpdate(FlowButton flowButton) {
        Flow flow = flowMapper.selectById(flowButton.getFlowId());
        if (flow != null) {
            CacheUtils.remove(CacheUtils.FLOW_BUTTON_CACHE, flow.getCode());
        }
        return super.saveOrUpdate(flowButton);
    }

    @Override
    public Map getByFlowKey(String flowKey) {
        Map<String, Object> map = new HashMap();
        Flow flow = flowMapper.selectOne(Wrappers.<Flow>query().eq("code",flowKey));
        if (flow == null) { throw new BusinessException("未能检索到流程：" + flowKey); }
        List<FlowButton> flowButtons = this.list(Wrappers.<FlowButton>query().eq("flow_id", flow.getId()));
        map.put("flow", flow);
        map.put("flowButtons", flowButtons);
        return map;
    }

    @Override
    public List<FlowButton> getByFlowId(String flowId) {
        return this.list(Wrappers.<FlowButton>query().eq("flow_id", flowId));
    }

    @Override
    public List<FlowButton> getByFlowCode(String flowCode) {
        Flow flow = flowMapper.selectOne(Wrappers.<Flow>query().eq("code", flowCode));
        if (flow == null) {
            return null;
        }
        return this.list(Wrappers.<FlowButton>query().eq("flow_id", flow.getId()));
    }

    @Override
    public boolean removeCascadeByIds(Collection<? extends Serializable> idList) {
        if (idList.isEmpty()) {
            return false;
        }
        List<FlowButton> flowButtons = this.list(Wrappers.<FlowButton>query().in("id", idList));
        if (!flowButtons.isEmpty()) {
            Flow flow = flowMapper.selectById(flowButtons.get(0).getFlowId());
            if (flow != null) {
                CacheUtils.remove(CacheUtils.FLOW_BUTTON_CACHE, flow.getCode());
            }
        }
        return super.removeCascadeByIds(idList);
    }

    @Override
    public Boolean isSupport(Boolean flagProject) {
        return flagProject;
    }
}
